package com.zhiche.wms.service.common.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.zhiche.wms.configuration.MyConfigurationProperties;
import com.zhiche.wms.core.supports.enums.InterfaceAddrEnum;
import com.zhiche.wms.core.supports.enums.InterfaceEventEnum;
import com.zhiche.wms.core.supports.enums.TableStatusEnum;
import com.zhiche.wms.core.utils.SnowFlakeId;
import com.zhiche.wms.domain.mapper.log.ItfExplogLineMapper;
import com.zhiche.wms.domain.model.log.ItfExplogHeader;
import com.zhiche.wms.domain.model.log.ItfExplogLine;
import com.zhiche.wms.domain.model.otm.OtmOrderRelease;
import com.zhiche.wms.dto.opbaas.resultdto.ShipmentForShipDTO;
import com.zhiche.wms.service.common.IntegrationService;
import com.zhiche.wms.service.dto.OTMEvent;
import com.zhiche.wms.service.dto.ShipParamDTO;
import com.zhiche.wms.service.log.IItfExplogHeaderService;
import com.zhiche.wms.service.utils.BusinessNodeExport;
import com.zhiche.wms.service.utils.CommonMethod;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
public class IntegrationServiceImpl implements IntegrationService {
    private static final Logger LOGGER = LoggerFactory.getLogger(IntegrationServiceImpl.class);

    @Autowired
    private SnowFlakeId flakeId;
    @Autowired
    private MyConfigurationProperties properties;
    @Autowired
    private IItfExplogHeaderService explogHeaderService;
    @Autowired
    private ItfExplogLineMapper itfExplogLineMapper;
    @Autowired
    private BusinessNodeExport nodeExport;
    @Autowired
    private IntegrationService integrationService;

    @Override
    public void toOtmBms (ShipmentForShipDTO shipmentForShipDTO, OtmOrderRelease oor, String shipTime, String userName) {
        new Thread(() -> {
            OTMEvent otmEvent = getOtmEvent(String.valueOf(oor.getId()), oor.getReleaseGid(), InterfaceEventEnum.BS_OP_DELIVERY.getCode(),
                    oor.getShipmentGid(), "已发运回传OTM/BMS");
            if (StringUtils.isNotEmpty(shipTime)) {
                otmEvent.setRecdDate(CommonMethod.getDate(shipTime));
                otmEvent.setOccurDate(CommonMethod.getDate(shipTime));
            }
            //调整参数--BMS传递更多信息
            ShipParamDTO paramDTO = buildBMSShipParam(shipmentForShipDTO, oor, otmEvent);
            if (StringUtils.isNotEmpty(shipTime)) {
                paramDTO.setShipTime(CommonMethod.getOTMShipTme(shipTime));
            }

            //推送otm
            String res = nodeExport.exportEventToOTMNew(paramDTO);

            //查询是否已有推送日志，已有则不需要推送
            EntityWrapper<ItfExplogLine> wifEw = new EntityWrapper<>();
            wifEw.eq("relation_id", oor.getId());
            wifEw.eq("export_type", InterfaceEventEnum.BS_OP_DELIVERY.getCode());
            List<ItfExplogLine> itfExplogLines = itfExplogLineMapper.selectList(wifEw);
            if (CollectionUtils.isEmpty(itfExplogLines)) {
                String message = "已发运回传OTM/BMS";
                integrationService.insertExportLogNew(String.valueOf(oor.getId()), paramDTO, res, message,
                        InterfaceEventEnum.BS_OP_DELIVERY.getCode(), userName, null);
            }
        }).start();
    }

    private ShipParamDTO buildBMSShipParam (ShipmentForShipDTO shipDTO, OtmOrderRelease oor, OTMEvent otmEvent) {
        ShipParamDTO paramDTO = new ShipParamDTO();
        paramDTO.setPlateNo(shipDTO.getPlateNo());
        paramDTO.setTrailerNo(shipDTO.getTrailerNo());
        paramDTO.setDriverGid(shipDTO.getDriverGid());
        paramDTO.setProviderGid(shipDTO.getServiceProviderGid());
        paramDTO.setVin(oor.getVin());
        paramDTO.setVehicleName(oor.getStanVehicleType());
        paramDTO.setOriginProvince(oor.getOriginLocationProvince());
        paramDTO.setOriginCity(oor.getOriginLocationCity());
        paramDTO.setOriginCounty(oor.getOriginLocationCounty());
        paramDTO.setOriginAddr(oor.getOriginLocationAddress());
        paramDTO.setDestProvince(oor.getDestLocationProvince());
        paramDTO.setDestCity(oor.getDestLocationCity());
        paramDTO.setDestCounty(oor.getDestLocationCounty());
        paramDTO.setDestAddr(oor.getDestLocationAddress());
        paramDTO.setOriginCode(oor.getOriginLocationGid());
        paramDTO.setDestCode(oor.getDestLocationGid());
        paramDTO.setCusOrderNo(oor.getCusOrderNo());
        paramDTO.setCusWaybill(oor.getCusWaybillNo());
        paramDTO.setExportKey(otmEvent.getExportKey());
        paramDTO.setCallBackUrl(otmEvent.getCallBackUrl());
        paramDTO.setEventType(otmEvent.getEventType());
        paramDTO.setOccurDate(otmEvent.getOccurDate());
        paramDTO.setRecdDate(otmEvent.getRecdDate());
        paramDTO.setSort(otmEvent.getSort());
        paramDTO.setDescribe(otmEvent.getDescribe());
        paramDTO.setOrderReleaseId(otmEvent.getOrderReleaseId());
        paramDTO.setShipmentId(otmEvent.getShipmentId());
        paramDTO.setQrCode(otmEvent.getQrCode());
        paramDTO.setShipTime(String.valueOf(new Date().getTime()));
        return paramDTO;
    }

    @Override
    public OTMEvent getOtmEvent(String key,
                                String releaseGid,
                                String eventType,
                                String shipmentGid,
                                String describe) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        OTMEvent event = new OTMEvent();
        event.setExportKey(String.valueOf(key));
        event.setCallBackUrl(null);
        event.setSort(1);
        event.setEventType(eventType);
        event.setOccurDate(sdf.format(new Date()));
        event.setRecdDate(sdf.format(new Date()));
        event.setDescribe(describe);
        event.setOrderReleaseId(releaseGid);
        event.setShipmentId(shipmentGid);
        return event;
    }

    @Override
    public void insertExportLog(String key,
                                OTMEvent event,
                                String res,
                                String describe,
                                String exportType) {
        ItfExplogHeader exH = new ItfExplogHeader();
        String jsonString = JSONObject.toJSONString(event);
        exH.setId(flakeId.nextId());
        exH.setExportType(exportType);
        exH.setRelationId(Long.valueOf(key));
        exH.setTargetSource(TableStatusEnum.STATUS_10.getCode());
        exH.setExportStatus(TableStatusEnum.STATUS_1.getCode());
        exH.setExportRemarks(describe);
        exH.setRequestId(res);

        ItfExplogLine exl = new ItfExplogLine();
        exl.setId(flakeId.nextId());
        exl.setHeaderId(exH.getId());
        exl.setExportType(exportType);
        exl.setRelationId(Long.valueOf(key));
        exl.setTargetSource(TableStatusEnum.STATUS_10.getCode());
        exl.setInterfaceUrl(properties.getIntegrationhost() + InterfaceAddrEnum.EVENT_URI.getAddress());
        exl.setExportStartTime(new Date());
        exl.setExportStatus(TableStatusEnum.STATUS_1.getCode());
        exl.setExportRemarks(describe);
        exl.setDataContent(jsonString);
        exl.setRequestId(res);
        ArrayList<ItfExplogLine> lines = Lists.newArrayList();
        lines.add(exl);
        exH.setItfExplogLines(lines);
        explogHeaderService.insertWithLines(exH);
    }

    @Override
    public void insertExportLogNew (String key,
                                    ShipParamDTO paramDTO,
                                    String res, String describe,
                                    String exportType, String userName,String pushUrl) {
        LOGGER.info("记录推送日志类型为{}记录相关主键id为{}",describe,key);
        String jsonString = JSONObject.toJSONString(paramDTO);
        ItfExplogHeader exH = new ItfExplogHeader();
        exH.setId(flakeId.nextId());
        exH.setExportType(exportType);
        exH.setRelationId(Long.valueOf(key));
        exH.setTargetSource(TableStatusEnum.STATUS_10.getCode());
        exH.setExportStatus(TableStatusEnum.STATUS_1.getCode());
        exH.setExportRemarks(describe);
        exH.setRequestId(res);

        ItfExplogLine exl = new ItfExplogLine();
        exl.setId(flakeId.nextId());
        exl.setHeaderId(exH.getId());
        exl.setExportType(exportType);
        exl.setRelationId(Long.valueOf(key));
        exl.setTargetSource(TableStatusEnum.STATUS_10.getCode());
        if(Objects.isNull(pushUrl) && StringUtils.isEmpty(pushUrl)){
            exl.setInterfaceUrl(properties.getIntegrationhost() + InterfaceAddrEnum.EVENT_URI.getAddress());
        }else {
            exl.setInterfaceUrl(pushUrl);
        }
        exl.setExportStartTime(new Date());
        exl.setExportStatus(TableStatusEnum.STATUS_1.getCode());
        exl.setExportRemarks(describe);
        exl.setDataContent(jsonString);
        exl.setRequestId(res);
        exl.setUserCreate(userName);
        ArrayList<ItfExplogLine> lines = Lists.newArrayList();
        lines.add(exl);
        exH.setItfExplogLines(lines);
        explogHeaderService.insertWithLines(exH);
        LOGGER.info("记录推送日志完成。。。。。。");
    }
}
